import React, { useState, useEffect, ChangeEvent, KeyboardEvent } from "react";
import useMap2D from "@/hooks/map/useMap2D";
import { fetchLayerTreeData } from "@/api/hap";
import { createLayer } from "@/utils/gis/CreateLayer";
import { layersStore } from "@/redux/features/layersSlice";

/**
 * 定义 NumberInput 组件的 Props 接口
 */
interface NumberInputProps {
  /** 输入框的值，可以是数字或空字符串 */
  value?: number | string;
  /** 当值有效变化时调用的回调函数，参数为最新的数值（或 null） */
  onChange: (value: number | null) => void;
  /** 输入框占位符 */
  placeholder?: string;
  /** 是否禁用 */
  disabled?: boolean;
  /** 自定义CSS类名 */
  className?: string;
  /** 允许传入任何标准的 input 元素属性 */
  [key: string]: any;

  filterLayer: (value: number) => void;
}

interface LayerItem {
  id: string;
  name: string;
  featureUrl: string;
  iconUrl: string;
  visible: string;
  layerVisible: boolean;
}

// 获取图层数据
const getLayerTreeData = async (callback: any) => {
  try {
    const data = await fetchLayerTreeData();
    const targetList = data.filter((item: any) => {
      item.layerVisible = false;
      return item.visible !== "false";
    });
    console.log(targetList);

    callback(targetList);
  } catch (error) {
    console.error("加载图层数据失败:", error);
  }
};

/**
 * 一个只接受数字输入的React组件。
 * 它是一个受控组件，并通过 onChange 回调传递最新的数值。
 */
const NumberInput: React.FC<NumberInputProps> = ({
  value = "",
  onChange,
  placeholder = "请输入数字",
  disabled = false,
  className = "",
  filterLayer,
  ...restProps
}) => {
  // 使用内部 state 来管理输入框的显示值
  const [inputValue, setInputValue] = useState<string>(String(value || ""));

  const [layerTreeList, setLayerTreeList] = useState<LayerItem[]>([]);
  const [allLayers, setAllLayers] = useState<any[]>([]);

  const { map2D, view2D } = useMap2D();

  // 当外部传入的 value prop 发生变化时，同步更新内部 state
  useEffect(() => {
    setInputValue(String(value || ""));
  }, [value]);

  // 单独处理图层数据的获取
  useEffect(() => {
    if (map2D && view2D) {
      getLayerTreeData(setLayerTreeList);
    }
  }, [map2D, view2D]);

  /**
   * 处理输入框内容变化
   * @param event - React ChangeEvent
   */
  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value;

    if (newValue === "") {
      setInputValue("");
      onChange(null);
      return;
    }

    const isValidNumber = /^-?\d*\.?\d*$/.test(newValue);

    if (isValidNumber) {
      setInputValue(newValue);
      const numericValue = parseFloat(newValue);
      onChange(isNaN(numericValue) ? null : numericValue);
    }
  };

  /**
   * 阻止非数字相关的按键输入
   * @param event - React KeyboardEvent
   */
  const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    const allowedKeys = [
      "Backspace",
      "Delete",
      "Tab",
      "Escape",
      "Enter",
      "ArrowLeft",
      "ArrowRight",
      "ArrowUp",
      "ArrowDown",
      "Home",
      "End",
    ];

    if (
      !allowedKeys.includes(event.key) &&
      !/[0-9]/.test(event.key) &&
      event.key !== "." &&
      event.key !== "-"
    ) {
      event.preventDefault();
    }

    // 特殊处理负号：只允许在开头输入
    if (event.key === "-" && event.currentTarget.selectionStart !== 0) {
      event.preventDefault();
    }

    // 特殊处理小数点：只允许输入一个小数点
    if (event.key === "." && inputValue.includes(".")) {
      event.preventDefault();
    }
  };

  /**
   * 处理checkbox状态变化
   * 关键修复：创建新的数组和对象来触发重新渲染
   */
  const handleCheckboxChange = (item: LayerItem, index: number) => {
    const layerTitle = item.name;
    const existingLayer = allLayers.find((layer) => layer.title === layerTitle);

    const newLayerVisible = !item.layerVisible;

    // 更新图层树列表 - 创建新数组和新对象
    setLayerTreeList((prevList) =>
      prevList.map((listItem, idx) =>
        idx === index
          ? { ...listItem, layerVisible: newLayerVisible }
          : listItem
      )
    );

    if (existingLayer) {
      // 更新现有图层的可见性
      existingLayer.visible = newLayerVisible;
    } else {
      // 创建新图层
      const newLayer = createLayer({
        type: "feature-point",
        url: item.featureUrl,
        title: item.name,
        visible: true,
        renderer: {
          type: "simple",
          symbol: {
            type: "picture-marker",
            url: item.iconUrl,
            width: 24,
            height: 24,
          },
        },
      });

      if (newLayer) {
        // 更新所有图层列表
        setAllLayers((prevLayers) => [...prevLayers, newLayer]);
        map2D?.add(newLayer);
        layersStore.addLayer(newLayer);
        console.log("create layer", newLayer);
      }
    }

    filterLayer(Number(inputValue));
  };

  return (
    <div className="content">
      <input
        type="text"
        style={{ width: "100%" }}
        value={inputValue}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
        disabled={disabled}
        className="number-input"
        {...restProps}
      />
      <div className="layer-content">
        {layerTreeList.map((item: LayerItem, index: number) => (
          <div key={item.id || index} className="layer-item">
            <input
              type="checkbox"
              checked={item.layerVisible || false}
              onChange={() => handleCheckboxChange(item, index)}
            />
            {item.name && <span className="layer-name">{item.name}</span>}
          </div>
        ))}
      </div>
    </div>
  );
};

export default NumberInput;